package com.cloudfast.platform.user.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cloudfast.common.date.DateUtils;
import com.cloudfast.common.decode.DecodeUtils;
import com.cloudfast.common.encode.EncodeUtils;
import com.cloudfast.common.page.Page;
import com.cloudfast.common.result.ApiResponse;
import com.cloudfast.common.user.UserUtils;
import com.cloudfast.context.error.CloudException;
import com.cloudfast.context.error.ErrorCode;
import com.cloudfast.controller.BaseController;
import com.cloudfast.platform.user.entity.User;
import com.cloudfast.platform.user.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * @author liuyw
 * @描述:用户管理
 * @date 2020年4月10日
 */
@RestController
@RequestMapping(value = "user")
@Api(value = "用户管理", tags = "用户管理")
public class UserController extends BaseController<User> {

    @Autowired
    private UserService userService;

    @Override
    public ApiResponse findPage(Page<User> page, User entity) {
        try {
            return ApiResponse.success(this.userService.findPage(page, entity));
        } catch (Exception e) {
            throw new CloudException(ErrorCode.FIND_PAGE_ERROR);
        }
    }

    @Override
    public ApiResponse save(User entity) {
        try {
            this.userService.save(entity);
            return ApiResponse.success(true);
        } catch (Exception e) {
            throw new CloudException(ErrorCode.SAVE_ERROR);
        }
    }

    @Override
    public ApiResponse findOne(Long id) {
        try {
            return ApiResponse.success(userService.findOne(id));
        } catch (Exception e) {
            throw new CloudException(ErrorCode.FIND_ONE_ERROR);
        }
    }


    /**
     * 服务之间调用的方法
     */
    @PostMapping("findOneUser")
    @ApiIgnore
    public User findOneUser(Long id) {
        try {
            return userService.findOne(id);
        } catch (Exception e) {
            throw new CloudException(ErrorCode.FIND_ONE_ERROR);
        }
    }

    @Override
    public ApiResponse delete(Long id) {
        try {
            userService.delete(id);
            return ApiResponse.success("");
        } catch (Exception e) {
            throw new CloudException(ErrorCode.DELETE_ERROR);
        }
    }

    /**
     * @param entity
     * @return
     * @描述:重设密码
     * @author liuyw
     * @date 2020年4月20日
     */
    @PostMapping(value = "saveNewPw")
    @ApiOperation("修改用户密码")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "用户主键", required = true),
            @ApiImplicitParam(name = "oldPwdCode", value = "旧密码", required = false),
            @ApiImplicitParam(name = "password", value = "用户密码", required = false),})
    public ApiResponse saveNewPw(@ApiIgnore User entity, String oldPwdCode) {
        try {
            Long id = UserUtils.getUser().getId();
            if (entity.getId() != null) {
                id = entity.getId();
            }
            if (StringUtils.isNotEmpty(oldPwdCode)
                    && !DecodeUtils.matches(oldPwdCode, userService.findOne(id).getPassword())) {
                return ApiResponse.error("旧密码错误");
            } else if (StringUtils.isEmpty(entity.getPassword())) {
                entity.setPassword(entity.getUsername().substring(0, 1).toUpperCase()
                        + entity.getUsername().substring(1, entity.getUsername().length()) + "@"
                        + DateUtils.getDate("yyyy"));
            }
            userService.saveNewPw(id, EncodeUtils.encode(entity.getPassword()));

            return ApiResponse.success("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new CloudException(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * @param id
     * @param username
     * @return
     * @描述:验证用户名是否存在
     * @author liuyw
     * @date 2020年4月20日
     */
    @PostMapping(value = "/checkUserName")
    @ApiOperation("检测用户名是否存在")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "用户主键", required = true),
            @ApiImplicitParam(name = "username", value = "用户账号", required = true)})
    public ApiResponse checkUserName(Long id, String username) {
        try {
            return ApiResponse.success(userService.checkUsername(id, username));
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new CloudException(ErrorCode.SYSTEM_ERROR);
        }
    }

    @PostMapping(value = "findRoleUser")
    @ApiOperation("用户拥有的角色")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "用户id", required = true)})
    public ApiResponse findRoleUser(Long userId) {
        try {
            return ApiResponse.success(this.userService.findRoleByUserId(userId));
        } catch (Exception e) {
            throw new CloudException(ErrorCode.SYSTEM_ERROR);
        }
    }

    @Override
    public ApiResponse findList(User entity) {
        try {
            return ApiResponse.success(this.userService.findList(entity));
        } catch (Exception e) {
            throw new CloudException(ErrorCode.SYSTEM_ERROR);
        }
    }
}
